<?php defined('SYSPATH') or die('No direct script access.');

class Article_Controller extends Template_Controller 
{
	private static $photo_path = '../photo/article';
	private static $resource_path = '../resource/article';
	
	public function __construct()
	{
		parent::__construct();
		
		// Add the menu to the template
		$this->template->menu = new View('menu');
		$this->template->content = '';
	}
	
	public function index()
	{
		self::lists(1);
		/*$dir = DOCROOT.'../photo/article';
		echo '<pre>';
		print_r(myfile::move_photo($dir, $file));
		echo '</pre>';*/
	}
	
	public function lists($page_no)
	{		
	    $model = new Article_Model();
	    $block = new Block_Model();
		
		$page_sizes = 10;
		
		$this->pagination = new Pagination(array(
	        'base_url'    => 'article/lists/', 
	        'uri_segment' => 3, 
			'items_per_page' => $page_sizes, 
	        'total_items' => $model->select('COUNT(*) AS records_found')->find()->records_found
	    ));
	 
		$view = new View('article/lists');
		$view->datas = $model->orderby('updated_at', 'DESC')->limit($page_sizes, (($page_no - 1) * $page_sizes))->find_all();
		$view->blocks = self::getBlocksBySourceName('articles');
		$view->categories = self::getArticleCategory();
		$view->type = '';
		$view->id = '';
		
		$this->template->content = $view->render();
	}
		
	public function view($id)
	{
		$view = new View('article/view');
		$view->article = new Article_Model($id);
		
		$this->template->content = $view->render();
	}
	
	public function create()
	{
		$form = new Forge(NULL, 'New Article');
		$form->input('name')->label(TRUE);
		$form->textarea('title_cn')->label('Chinese Title')->rules('required');
		$form->textarea('title_en')->label('English Title')->rules('required');
		$form->textarea('highlight_cn')->label('Chinese Highligt');
		$form->textarea('highlight_en')->label('English Highligt');
		$form->textarea('content_cn')->label('Chinese Content');
		$form->textarea('content_en')->label('English Content');
		$form->input('link')->label('URL Link');
		$form->upload('file', TRUE)->label('Photo')->rules('size[2000KB]|allow[jpg,png,gif]');
		$form->submit('Save');
 
		if($form->validate())
		{
			//Load model and set values
			$model = new Article_Model();
			$model->name = $form->name->value;
			$model->title_cn = $form->title_cn->value;
			$model->title_en = $form->title_en->value;
			$model->highlight_cn = $form->highlight_cn->value;
			$model->highlight_en = $form->highlight_en->value;
			$model->content_cn = $form->content_cn->value;
			$model->content_en = $form->content_en->value;
			$model->link = $form->link->value;
			$model->created_at = date('Y-m-d H:i:s');
 
			//Save form into table
			if($model->save())
			{
				if($form->file->value)
				{
					$extension = strtolower(file::extension($form->file->value));
					$filename = DOCROOT.self::$resource_path.'/'.$model->id.'.'.$extension;
					myfile::move($form->file->value, $filename);
					$model->photo_ext = $extension;
					$model->save();
					myfile::move_photo(DOCROOT.self::$photo_path, $model->id.'.'.$extension);
				}
				
				url::redirect('article');
				exit;
			}
			else
			{
				echo 'no saving today';
			}
		}
		else
		{
		    $this->template->content = $form->html();
		}
	}
	
	public function edit($id)
	{
		$model = new Article_Model($id);

		$form = new Forge(NULL, 'Edit Attribute');
		$form->input('name')->label('Name')->value($model->name);
		$form->textarea('title_cn')->label('Chinese Title')->rules('required')->value($model->title_cn);
		$form->textarea('title_en')->label('English Title')->rules('required')->value($model->title_en);
		$form->textarea('highlight_cn')->label('Chinese Highligt')->value($model->highlight_cn);
		$form->textarea('highlight_en')->label('English Highligt')->value($model->highlight_en);
		$form->textarea('content_cn')->label('Chinese Content')->value($model->content_cn);
		$form->textarea('content_en')->label('English Content')->value($model->content_en);
		$form->input('link')->label('URL Link')->value($model->link);
		$form->upload('file', TRUE)->label('Photo')->rules('size[2000KB]|allow[jpg,png,gif]');
		$form->submit('Save');
 
		if($form->validate())
		{
			$model->name = $form->name->value;
			$model->title_cn = $form->title_cn->value;
			$model->title_en = $form->title_en->value;
			$model->highlight_cn = $form->highlight_cn->value;
			$model->highlight_en = $form->highlight_en->value;
			$model->content_cn = $form->content_cn->value;
			$model->content_en = $form->content_en->value;
			$model->link = $form->link->value;
 
			//Save form into table
			if($model->save())
			{
				if($form->file->value)
				{
					$extension = strtolower(file::extension($form->file->value));
					$filename = DOCROOT.self::$resource_path.'/'.$model->id.'.'.$extension;
					myfile::move($form->file->value, $filename);
					$model->photo_ext = $extension;
					$model->save();
					myfile::move_photo(DOCROOT.self::$photo_path, $model->id.'.'.$extension);
				}
				
				url::redirect('article/view/'.$id, 301);
				exit;
			}
			else
			{
				echo 'no saving today';
			}
		}
		else
		{
		    $this->template->content = $form->html();
		}
	}
	
	public function editcontent($id, $lang_code)
	{
		if(!isset($_POST['content_'.$lang_code]))
		{
			$view = new View('article/edit_content');
			$view->article = new Article_Model($id);
			$view->lang_code = $lang_code;
		
			$this->template->content = $view->render();
		}
		else
		{
			$model = new Article_Model($id);
			$content = 'content_'.$lang_code;
			$model->$content = $_POST['content_'.$lang_code];
			$model->save();
			url::redirect('article/view/'.$id, 301);
		}
	}
	
	public function delete_photo($article_id)
	{
		$article = new Article_Model($article_id);
		
		$photo = DOCROOT.self::$resource_path.'/'.$article->id.'.'.$article->photo_ext;
		
		if(file_exists($photo))
		{
			if(unlink($photo))
			{
				myfile::move_photo(DOCROOT.self::$photo_path, $article_id.'.'.$article->photo_ext);
				$article->photo_ext = '';
				$article->save();
			}
		}
		
		url::redirect('article/view/'.$article_id, 301);
	}
	
	public function delete($id)
	{
		$attribute = new Article_Model($id);
		$attribute->delete();
		
		url::redirect('article', 301);
	}

	public function search()
	{
		if(isset($_POST['keyword']) and trim($_POST['keyword']) != '')
		{
		    $block = new Block_Model();
		    $article = new Article_Model();
			
			$view = new View('article/lists');
		
			$view->caption = 'Article List --- 搜索关键词：'.$_POST['type'].' 中包含 "'.$_POST['keyword'].'"';
			
			switch ($_POST['type'])
			{
				case 'id':
					$view->datas = $article->where('id', intval($_POST['keyword']))->find_all();
					break;
				case 'title':
					$view->datas = $article->where("title_cn LIKE '%".$_POST['keyword']."%'")
										   ->orwhere("title_en LIKE '%".$_POST['keyword']."%'")
										   ->orwhere("name LIKE '%".$_POST['keyword']."%'")
										   ->orderby('updated_at', 'DESC')
										   ->find_all();
					break;
				case 'name':
					$view->datas = $article->where("name LIKE '%".$_POST['keyword']."%'")
										   ->orderby('updated_at', 'DESC')
										   ->find_all();
					break;
			}
		
			$view->id = '';
			$view->type = '';
			$view->categories = self::getArticleCategory();
			$view->blocks = self::getBlocksBySourceName('articles');
			
			$this->template->content = $view->render();
		}
		else
		{
			url::redirect('article');
			exit;
		}
	}
	
	public function filter($type, $id, $page_no)
	{
		if($id==0)
		{
			url::redirect('article');
			exit;
		}
		
	    $block = new Block_Model();
	    $article = new Article_Model();
	 
		$view = new View('article/lists');
		
		switch ($type) 
		{
			case 'category':
				$category = new Article_Category_Model($id);
				$view->caption = 'Article List --- 分类名称：'.$category->title_cn;
				$this->pagination = new Pagination(array(
			        'base_url'    => 'article/filter/'.$type.'/'.$id, 
			        'uri_segment' => 5, 
					'items_per_page' => 10, 
			        'total_items' => $article->select('COUNT(*) AS records_found')
											 ->join('articles_categories AS ac', 'ac.article_id=articles.id')
											 ->where('ac.category_id', $id)
											 ->find()->records_found
			    ));
				$view->datas = $article->join('articles_categories AS ac', 'ac.article_id=articles.id')
									   ->where('ac.category_id', $id)
									   ->orderby('updated_at', 'DESC')
									   ->limit(10, (($page_no - 1) * 10))
									   ->find_all();
				break;
			case 'block':
				$b = new Block_Model($id);
				$view->caption = 'Article List --- 版块名称：'.$b->title;
				$this->pagination = new Pagination(array(
			        'base_url'    => 'article/filter/'.$type.'/'.$id, 
			        'uri_segment' => 5, 
					'items_per_page' => 10, 
			        'total_items' => $article->select('COUNT(*) AS records_found')
											 ->join('block_elements AS be', 'be.source_pk_id=articles.id')
									   		 ->where('be.block_id', $id)
											 ->find()->records_found
			    ));
				$view->datas = $article->join('block_elements AS be', 'be.source_pk_id=articles.id')
									   ->where('be.block_id', $id)
									   ->orderby('updated_at', 'DESC')
									   ->limit(10, (($page_no - 1) * 10))
									   ->find_all();
				break;
				
		}
		
		$view->id = $id;
		$view->type = $type;
		$view->categories = self::getArticleCategory();
		$view->blocks = self::getBlocksBySourceName('articles');
		
		$this->template->content = $view->render();
	}
	
	protected function getBlocksBySourceName($source_name)
	{
		$block = new Block_Model();
		$result = $block->where('source_name', $source_name)
						->find_all();
		
		$arr['0'] = '';
		
		foreach($result as $record)
		{
			$arr[$record->id] = $record->title;
		}

		return $arr;
	}
	
	protected function getArticleCategory()
	{
		$model = new Article_Category_Model();
		$result = $model->where('left_id>1')
						->where('right_id < (SELECT right_id FROM article_categories WHERE id=1)')
						->where('layer_id<=2')
						->orderby('left_id')
						->find_all();
		
		$arr['cn']['0'] = '';
		$arr['en']['0'] = '';
		
		foreach($result as $record)
		{
			if($record->layer_id == 1)
			{
				if(($record->right_id-$record->left_id) == 1)
				{
					$arr['cn'][$record->id] = $record->title_cn;
					$arr['en'][$record->id] = $record->title_en;
				}
				else
				{
					$arr['cn'][$record->title_cn] = array();
					$arr['en'][$record->title_en] = array();
					$parent_cn = $record->title_cn;
					$parent_en = $record->title_en;
				}
			}
			elseif ($record->layer_id == 2)
			{
				$arr['cn'][$parent_cn][$record->id] = $record->title_cn;
				$arr['en'][$parent_en][$record->id] = $record->title_en;
			}
		}

		return $arr['cn'];
	}
}